# -*- coding: utf-8 -*-

students = []  # 主列表存储所有学生信息


def add_stu():
    """添加学生信息"""
    print("\n--- 添加学生信息 ---")
    while True:
        try:
            # 基本信息
            student_id = input("请输入学号: ").strip()
            name = input("请输入姓名: ").strip()
            class_name = input("请输入班级: ").strip()

            # 实验成绩（3次）
            experiments = []
            print("请输入3次实验成绩:")
            for i in range(1, 4):
                score = float(input(f"实验{i}: "))
                experiments.append(score)

            # 创建学生字典
            student = {
                'student_id': student_id,
                'name': name,
                'class': class_name,
                'experiments': experiments
            }

            students.append(student)
            print(f"成功添加学生: {name} (学号: {student_id})")

            another = input("是否继续添加？(y/n): ").strip().lower()
            if another != 'y':
                break

        except ValueError:
            print("输入错误！成绩必须是数字，请重新输入。")
        except KeyboardInterrupt:
            print("\n操作已取消")
            break


def show_all():
    """显示所有学生信息"""
    print("\n--- 所有学生信息 ---")
    if not students:
        print("暂无学生信息！")
        return

    # 打印表头
    header = f"{'序号':<4} {'学号':<12} {'姓名':<8} {'班级':<6} "
    # 实验成绩
    for i in range(1, 4):
        header += f"{'实验' + str(i):<6}"

    print(header)
    print("-" * 50)

    # 打印每个学生的信息
    for i, student in enumerate(students, 1):
        row = f"{i:<4} {student['student_id']:<12} {student['name']:<8} {student['class']:<6} "

        # 实验成绩
        for exp in student['experiments']:
            row += f"{exp:<6.0f}"

        print(row)


def search_stu():
    """搜索学生信息"""
    print("\n--- 搜索学生信息 ---")
    if not students:
        print("暂无学生信息！")
        return

    keyword = input("请输入要搜索的学生学号或姓名: ").strip()
    found = [s for s in students if keyword in s['student_id'] or keyword in s['name']]

    if not found:
        print(f"未找到相关学生！")
        return

    # 打印表头
    header = f"{'学号':<12} {'姓名':<8} {'班级':<6} "
    # 实验成绩
    for i in range(1, 4):
        header += f"{'实验' + str(i):<6}"

    print(header)
    print("-" * 50)

    for student in found:
        row = f"{student['student_id']:<12} {student['name']:<8} {student['class']:<6} "

        # 实验成绩
        for exp in student['experiments']:
            row += f"{exp:<6.0f}"

        print(row)


def delete_stu():
    """删除学生信息"""
    print("\n--- 删除学生信息 ---")
    if not students:
        print("暂无学生信息！")
        return

    show_all()
    try:
        index = int(input("请输入要删除的学生序号: ")) - 1
        if 0 <= index < len(students):
            deleted = students.pop(index)
            print(f"已删除学生: {deleted['name']} (学号: {deleted['student_id']})")
        else:
            print("无效的序号！")
    except ValueError:
        print("请输入有效的数字！")


def save_to_file():
    """保存数据到文件"""
    try:
        with open("D:/python_code/pythonProject1/students.txt", "w", encoding="utf-8") as f:
            # 写入表头
            header = "学号,姓名,班级,"
            header += ",".join([f"实验{i}" for i in range(1, 4)]) + "\n"
            f.write(header)

            # 写入数据
            for student in students:
                line = f"{student['student_id']},{student['name']},{student['class']},"
                line += ",".join([str(exp) for exp in student['experiments']]) + "\n"
                f.write(line)
        print("数据已保存到 students.txt")
    except Exception as e:
        print(f"保存文件时出错: {e}")


def load_from_file():
    """从文件加载数据"""
    global students
    try:
        with open("students.txt", "r", encoding="utf-8") as f:
            lines = f.readlines()
            # 跳过表头
            for line in lines[1:]:
                data = line.strip().split(',')
                if len(data) >= 6:  # 确保有足够的数据项
                    student = {
                        'student_id': data[0],
                        'name': data[1],
                        'class': data[2],
                        'experiments': [float(x) for x in data[3:6]]
                    }
                    students.append(student)
        print("数据已从 students.txt 加载")
    except FileNotFoundError:
        print("未找到数据文件，将从空列表开始")
    except Exception as e:
        print(f"加载文件时出错: {e}")


def main():
    """主函数"""
    # 启动时加载数据
    load_from_file()

    while True:
        print("\n" + "=" * 50)
        print("          学生成绩管理系统")
        print("=" * 50)
        print("1. 添加学生")
        print("2. 查看所有学生")
        print("3. 搜索学生")
        print("4. 删除学生")
        print("5. 保存数据")
        print("6. 退出系统")
        print("=" * 50)

        choice = input("请选择操作 (1-6): ").strip()

        if choice == '1':
            add_stu()
        elif choice == '2':
            show_all()
        elif choice == '3':
            search_stu()
        elif choice == '4':
            delete_stu()
        elif choice == '5':
            save_to_file()
        elif choice == '6':
            save_to_file()  # 退出前自动保存
            print("感谢使用学生成绩管理系统，再见！")
            break
        else:
            print("无效选择，请重新输入！")


# 程序入口
if __name__ == "__main__":
    main()